package main

import (
	"fmt"
	"sync"
)

/*
单例模式
 */

type Instance struct {
	name string
}
var instance *Instance
var lock sync.Mutex
var once sync.Once


// 双重检查机制
func Single1() *Instance {
	if instance == nil {
		lock.Lock()
		defer lock.Unlock()
		if instance == nil {
			instance = &Instance{name:"hello"}
		}
	}
	return instance
}

func Single2() *Instance {
	once.Do(func() {
		instance = &Instance{name:"hello"}
	})
	return instance
}

func main() {
	i1 := Single2()
	fmt.Println(i1)

	i2 := Single2()
	fmt.Println(i2)
}
